const e = require("express");
const MySQLDatabase = require("../utils/dbconfig"); // 根据你的文件路径调整
const {formatTimeToChinaTime} = require("../utils/tools")
const fs = require('fs');       
const path = require('path');    
const yaml = require('js-yaml'); 

let mysqlConfig = {};

try {
    const fileContents = fs.readFileSync(path.resolve(__dirname, '../config.yml'), 'utf8');
    const config = yaml.load(fileContents);
    mysqlConfig = config.mysql;
    // console.log('✅ 配置加载成功:', mysqlConfig); 
} catch (e) {
    console.error('❌ 读取配置失败:', e);
}

const db = new MySQLDatabase({
    host: mysqlConfig.host,
    user: mysqlConfig.username,
    password: mysqlConfig.pwd, // ✅ 修复此处
    database: mysqlConfig.database
});


async function queryAllKeyWord() {
    let sql = "SELECT * FROM key_wrod_tab"
    try {
        const result = await db.query(sql)
        // 格式化 creation_time
    const formattedResult = result.map(item => ({
        ...item,
        creation_time: formatTimeToChinaTime(item.creation_time)
    }));
        return formattedResult
    } catch (err) {
        return "查询失败"
    }
}

async function insertKeyWrod(keyword,content) {
    const keys = {
        key_wrod: keyword,
        content : content
    };
    try {
        const result = await db.insert('key_wrod_tab', keys);
        return "新增成功";
    } catch (err) {
        return err.sqlMessage;
    }
}

async function delKeyWrod(id){
    try {
        const result = await db.delete('key_wrod_tab', "id = " + id,[1])
        return "删除成功"
    }catch(err){
        console.log(err)
        return err.sqlMessage;
    }
}


// (async () => {
//     console.log(11)
//    await queryAllKeyWord().then((res)=>{
//         console.log(res)
//     })
   
//     // console.log(22)
//     // let r =  await insertKeyWrod("测试5","asdasd");
//     // console.log(r); // 正确输出 “新增成功” 或错误信息
// })();

module.exports = {
    queryAllKeyWord,
    insertKeyWrod,
    delKeyWrod
}



// console.log(r)

// (async () => {

//     let res = await delKeyWrod(10)
//     console.log(res)

//     let r = await queryAllKeyWord()
//     console.log(r)

//     db.end()
// })();

// test()
